import React, {Component} from 'react';
import {
  Text,
  StyleSheet,
  View,
  SafeAreaView,
  Image,
  Dimensions,
  Alert,
  FlatList,
  TouchableOpacity,
} from 'react-native';
import Ionicons from 'react-native-vector-icons/Ionicons';
import Networking from '../Network/Requests';
import NetworkConfig from '../Network/NetworkConfig.json';

var pageNumber = 0;
var isLoadingMore = false;

interface DataModel {
  imageUrl: string;
  title: string;
  levelUrl: string;
  nickname: string;
}

interface StateType {
  isfresh: boolean;
  canLoadMore: boolean;
  data: DataModel[];
}

interface ResultsType {
  pagingState: number;
  elements: ElementsType[];
}

interface ElementsType {
  type: string;
  element: NineBlockElementsType | GraphicTextElementsType;
}

interface NineBlockElementsType {
  mainBody: string;
  shareDto: ShareDtoType;
  timelineAuthorDto: TimelineAuthorDtoType;
}

interface GraphicTextElementsType {
  type: string;
  title: string;
  coverImage: CoverImageType;
  timelineAuthorDto: TimelineAuthorDtoType;
}

interface ShareDtoType {
  imageUrl: string;
}

interface CoverImageType {
  imagePath: string;
}

interface TimelineAuthorDtoType {
  levelUrl: string;
  nickname: string;
}

export default class Home extends Component<any, StateType> {
  constructor(props: any) {
    super(props);
    this.state = {
      isfresh: false,
      canLoadMore: false,
      data: [],
    };
  }

  refreshingData = () => {
    pageNumber = 1;
    this.setState({
      isfresh: true,
    });
    Networking.loadData<ResultsType>(NetworkConfig.HotTopic, {
      pagingState: pageNumber,
    })
      .then((results: ResultsType) => {
        // console.log('Refreshing Data Response : ', results)
        var dataArray = [] as any;
        let pagingState = results.pagingState;
        results.elements.forEach(item => {
          if (item.type === 'NINE_BLOCK') {
            let element = item.element as NineBlockElementsType;
            let tempDic: DataModel = {
              imageUrl: element.shareDto.imageUrl,
              title: element.mainBody,
              levelUrl: element.timelineAuthorDto.levelUrl,
              nickname: element.timelineAuthorDto.nickname,
            };
            dataArray.push(tempDic);
          } else {
            let element = item.element as GraphicTextElementsType;
            let tempDic: DataModel = {
              imageUrl: element.coverImage.imagePath,
              title: element.title,
              levelUrl: element.timelineAuthorDto.levelUrl,
              nickname: element.timelineAuthorDto.nickname,
            };
            dataArray.push(tempDic);
          }
        });
        this.setState({
          isfresh: false,
          canLoadMore: pagingState != null,
          data: dataArray,
        });
      })
      .catch(error => {
        this.setState({
          isfresh: false,
        });
        Alert.alert('error:', error);
      });
  };

  loadMoreData = () => {
    isLoadingMore = true;
    pageNumber += 1;
    Networking.loadData<ResultsType>(NetworkConfig.HotTopic, {
      pagingState: pageNumber,
    })
      .then((results: ResultsType) => {
        // console.log('Load More Data Response : ', results)
        let pagingState = results.pagingState;
        results.elements.forEach(item => {
          if (item.type === 'NINE_BLOCK') {
            let element = item.element as NineBlockElementsType;
            let tempDic: DataModel = {
              imageUrl: element.shareDto.imageUrl,
              title: element.mainBody,
              levelUrl: element.timelineAuthorDto.levelUrl,
              nickname: element.timelineAuthorDto.nickname,
            };
            this.state.data.push(tempDic);
          } else {
            let element = item.element as GraphicTextElementsType;
            let tempDic: DataModel = {
              imageUrl: element.coverImage.imagePath,
              title: element.title,
              levelUrl: element.timelineAuthorDto.levelUrl,
              nickname: element.timelineAuthorDto.nickname,
            };
            this.state.data.push(tempDic);
          }
        });
        isLoadingMore = false;
        this.setState({
          canLoadMore: pagingState != null,
        });
      })
      .catch(error => {
        isLoadingMore = false;
        Alert.alert('error:', error);
      });
  };

  render(): React.ReactNode {
    return (
      <SafeAreaView style={styles.container}>
        <FlatList
          data={this.state.data}
          keyExtractor={(item: any, index: any) => item + index}
          numColumns={2}
          showsVerticalScrollIndicator={false}
          renderItem={({item}) => (
            <TouchableOpacity
              style={styles.item}
              onPress={() => {
                this.props.navigation.navigate('Detail', item);
              }}>
              <Text style={styles.title}> {item.title} </Text>
              <Image source={{uri: item.imageUrl}} style={styles.image} />
              <View style={styles.buttonView}>
                <TouchableOpacity
                  style={styles.button}
                  onPress={() => {
                    Alert.alert('已点赞!');
                  }}>
                  <Ionicons name="star-outline" />
                  <Text style={styles.buttonText}> 点赞 </Text>
                </TouchableOpacity>
                <TouchableOpacity
                  style={styles.button}
                  onPress={() => {
                    Alert.alert('已评论!');
                  }}>
                  <Ionicons name="chatbox-outline" />
                  <Text style={styles.buttonText}> 评论 </Text>
                </TouchableOpacity>
                <TouchableOpacity
                  style={styles.button}
                  onPress={() => {
                    Alert.alert('已收藏!');
                  }}>
                  <Ionicons name="bookmark-outline" />
                  <Text style={styles.buttonText}> 收藏 </Text>
                </TouchableOpacity>
              </View>
            </TouchableOpacity>
          )}
          ListHeaderComponent={() => {
            if (this.state.data.length === 0) {
              return null;
            }
            return (
              <View style={styles.header}>
                <Text style={styles.headerTitle}> 相关帖子 </Text>
              </View>
            );
          }}
          ListFooterComponent={() => {
            if (this.state.data.length === 0 || this.state.canLoadMore) {
              return null;
            }
            return (
              <View style={styles.footer}>
                <Text style={styles.footerTitle}> 全部加载完毕 </Text>
              </View>
            );
          }}
          // 没有数据
          ListEmptyComponent={() => {
            return (
              <View style={styles.emptyView}>
                <Ionicons
                  name={'file-tray-stacked-outline'}
                  color={'gray'}
                  size={65}
                />
                <Text style={styles.emptyTitle}> 暂无内容 </Text>
              </View>
            );
          }}
          // 下拉刷新
          refreshing={this.state.isfresh}
          onRefresh={this.refreshingData}
          // 上拉加载
          onEndReachedThreshold={50 / Dimensions.get('window').height} // 声明触底比例, 0.1表示距离底部还有10%
          onEndReached={({distanceFromEnd}) => {
            // console.log('offset : ', distanceFromEnd)
            if (distanceFromEnd <= 0 || isLoadingMore) return;
            // console.log('loadData : ', distanceFromEnd)
            this.loadMoreData();
          }}
        />
      </SafeAreaView>
    );
  }

  componentDidMount(): void {
    this.refreshingData();
  }
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    marginLeft: 10,
    marginRight: 10,
    height: Dimensions.get('screen').height,
  },
  header: {
    flex: 1,
    alignItems: 'center',
    justifyContent: 'center',
    height: 50,
    marginBottom: 10,
    borderRadius: 10,
    backgroundColor: 'white',
  },
  headerTitle: {
    fontSize: 20,
    fontWeight: '600',
    color: 'black',
  },
  footer: {
    flex: 1,
    alignItems: 'center',
    justifyContent: 'center',
    marginBottom: 10,
    height: 20,
  },
  footerTitle: {
    fontSize: 13,
    color: 'black',
  },
  item: {
    width: (Dimensions.get('window').width - 30) / 2,
    height: (Dimensions.get('window').width - 30) / 2 + 100,
    marginRight: 10,
    marginBottom: 10,
    borderRadius: 10,
    backgroundColor: 'white',
  },
  title: {
    height: 30,
    fontSize: 12,
    fontWeight: '500',
    margin: 10,
    flexWrap: 'nowrap',
  },
  image: {
    width: (Dimensions.get('window').width - 30) / 2,
    height: (Dimensions.get('window').width - 30) / 2,
  },
  buttonView: {
    flex: 1,
    flexDirection: 'row',
  },
  button: {
    flex: 1,
    width: (Dimensions.get('window').width - 30) / 6,
    flexDirection: 'row',
    alignItems: 'center',
    justifyContent: 'center',
  },
  buttonText: {
    fontSize: 12,
  },
  emptyView: {
    alignItems: 'center',
    justifyContent: 'center',
    height: 200,
    top: Dimensions.get('window').height / 2 - 200,
  },
  emptyTitle: {
    color: 'gray',
    margin: 10,
    fontSize: 16,
    fontWeight: '500',
  },
});
